package com.hbnu.net;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @author kittychen
 * @since 2025-10-28 19:09
 */
public class UdpReceiveDemo01 {

    public static void main(String[] args) {
        DatagramSocket datagramSocket = null;

        try {
            datagramSocket = new DatagramSocket(8888);
            while (true) {
                // 1、创建Socket

                // 2、准备容器，封装数据报包
                byte[] bytes = new byte[1024];
                DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);

                // 3、接收数据
                datagramSocket.receive(datagramPacket);   // receive方式是一个阻塞式方法

                // 4、解析数据
                String ip = datagramPacket.getAddress().getHostAddress();  // 获取发送方的ip地址
                int port = datagramPacket.getPort();  // 获取发送方的端口号
                String content = new String(datagramPacket.getData(), 0, datagramPacket.getLength());  // 获取发送方的数据
                System.out.println(ip + ":" + port + ":" + content);
                if ("886".equals(content)) {
                    break;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 5、关闭资源
            if (datagramSocket != null)
                datagramSocket.close();
        }
    }
}
